import React from "react";
import { Select,Button, Modal, Form, Col, Row, Input} from 'antd/lib';
import notification from "@/services/notification";
import {get} from "lodash";
import Uploads from "@/services/uploads";
import 'antd/dist/antd.less'
import moment from "moment";
import DatePicker from "antd/lib/date-picker";
import locale from 'antd/es/date-picker/locale/zh_CN';
import { currentUser } from "@/services/auth";
import ContractProgress from "@/services/contractprogress";
import Contracts from "@/services/contracts";
import ContractApply from "@/services/contractapply";
import WarningOutlined from "@ant-design/icons/WarningOutlined";
import Attaches from "@/services/attaches";
import {StarOutlined, UploadOutlined} from '@ant-design/icons';
import Upload from "antd/lib/upload";
const { confirm } = Modal;

export default class ProgressTable extends React.Component {
  state = {
    loading: true,
    id: "0",//
	  userid: currentUser.id,//--操作员ID
	  bill_date: moment(),//--申请日期
	  contractsid: "",
	  code: "",//----合同编号
	  name: "",//--合同名称
	  status: 0,//--状态
    percent:0,
	  message: "",//--纪录事项
    contractsdata:[],
    isCreateProgressEnabled: true,
    sourcetype: "",
    sourceid: 0,
    annex:[],//--附件
  };
  // componentDidMount() {
  //   const userId = this.props.userId || currentUser.id;
  // }
  componentWillMount() {
    let id=this.props.data.id;
    if(this.props.data.id<1 || this.props.data.id===undefined ){
      id=0;
    }
    let param={
      billtype: "contractprogress",
      id: id,
    }
    Contracts.getsellist(param).then(data => {
      this.setState({
        contractsdata: data,
      });
    });
    this.refreshData(this.props.data);
  }
  componentDidMount() {
    　　this.props.onRef(this);
  }
     // 这种方式十分适合父子组件的互动，通常是父组件需要通过某些状态控制子组件渲染亦或销毁...
componentWillReceiveProps(nextProps) {//componentWillReceiveProps方法中第一个参数代表即将传入的新的Props
    this.refreshData(nextProps.data);
}
  refreshData(data) {
          this.setState({
            id: data.id,//
            userid: data.userid,//--操作员ID
            bill_date: moment(data.bill_date),//--申请日期
            contractsid: data.contractsid,//--合同
            code: data.code,//----编号
            name: data.name,//--名称
            status: data.status,//--状态
            percent: data.percent,//
            message: data.message,//--纪录事项
            loading: false,
          });
          Attaches.get({sourceid:data.id,type:"contractprogress" }).then(data => {
            this.setState({
              annex: data.annex,
            });
          }).catch(error => {
                this.setState({
                  annex:[],//--附件
                });
          });
          if(data.code===""){
          let params = {
            tblname: "contractprogress",
            bill_date: moment(),
            type: 0,
            tblfield: "code",
          }
          this.getcode(params);
        }
  }
   getcode= (params) => {
  //  let params = {
  //    tblname: "contractprogress",
  //    bill_date: bill_date,
  //    type: "type",
  //    tblfield: "code",
  //  }
  if(!this.props.isnew){
    this.setState({
      bill_date: params.bill_date,
    });
    return;
  }
   ContractApply.getcode(params).then(data => {
     this.setState({
       code: data[0].code,
       bill_date: params.bill_date,
     });
   })
     .catch(error => {
     //  notification.error(error.message, error.detailedMessage);
     });
 }
 bill_dateonchange = (value) => {
  let params={
   tblname: "contractprogress",
   bill_date: value,
   type: 0,
   tblfield: "code",
 }
 this.getcode(params);
 };
  percentChange =e =>{
          this.setState({
            percent: e.target.value,
          });
  }
  handleDelete = record => {
    confirm({
      title: '确定删除合同违约登记单?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        // OrgUnit.delete(record).then(()=>{
        //   notification.success("合同申请单删除成功.");
        //   this.refreshData('',1);
        // }).catch(error => {
        //   notification.error(get(error, "response.data.message", "删除失败."));
        // });
      },
    });
  };
   handledown(file){
     let  filename=file.url;
     let names=file.name;
     if(names.split('.')[1]!==filename.split('.')[1]){
      filename=filename.split('.')[0] +'.'+names.split('.')[1];
     }
     let AjaxUrl = 'api/upload/downloadfile';
     fetch(AjaxUrl ,{
      method: 'POST',
      body: window.JSON.stringify({filename: filename}),
      credentials: 'include',
      headers: new Headers({
        'Content-Type': 'application/json'
      })}).then((response) => {
      response.blob().then(blob => {
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display='none';
        const objectUrl = window.URL.createObjectURL(blob);
        aLink.href = objectUrl;
        aLink.download = file.name;
        aLink.click();
        document.body.removeChild(aLink);
      });
    }).catch((error) => {
      console.log(error);
    });
  };
   getPdfURL(){
        const _this = this;
        const props = {
            name: 'file',
            action: 'api/upload/uploadfile/contractprogress/editor/0/0/'+_this.props.id,
            headers: {
                authorization: 'authorization-text',
            },
         //  onChange: this.handleChange,
         onChange(info) {
                let fileList = [...info.fileList];

                // 1. Limit the number of uploaded files
                // Only to show two recent uploaded files, and old ones will be replaced by the new
                // fileList = fileList.slice(-2);
                // 2. Read from response and show file link
            var newd=[];
            fileList.forEach(file => {
                  if (file.response) {
                    // Component will show file.url as link
                    file.url = 'static/file/'+file.response.filename;
                  }
                  let status = _this.state.status;
                  if(file.bytstatus>=0){
                    status=file.bytstatus;
                  }
             // if(file.status==="done") {
                 const b=[{
                          uid: file.uid,
                          name: file.name,
                          status: file.status,
                          bytstatus: status,
                          url: file.url
                  }];
                if (newd.length < 1) {
                  newd = b;
                } else {
                  newd.push.apply(newd, b);
                }
             // }
                });
                _this.setState({ annex:newd });
              },
           onDownload: this.handledown,
           onRemove(infos){
            let uid=infos.uid;
            const id=_this.props.id;
            Uploads.removefile({sourcetype: "contractprogress",sourceid:id,uid:uid}).then(data => {
                 if(data.code==="sucess"){
                    notification.success(data.msg);
                 }
                 else{
                  notification.error(data.msg);
                  }
                }).catch(error => {
                  notification.error(get(error, "response.data.message", "删除失败."));
                });
           },
            showUploadList: {
            showDownloadIcon: true,
            downloadIcon: '下载',
            showRemoveIcon: true,
            removeIcon: <StarOutlined onClick={e => console.log(e, 'custom removeIcon event')} />,
          },
        };
        return props;
    };
  fieldedit(field){
    if(!this.props.isedit){
      return true;
    }
    if(this.props.colcontrol){
      if(this.props.allow_col.indexOf(field)>=0){
        return false;
      }else{
        return true;
      }
    }else{
      return false;
    }
  }
  render() {
    if (this.state.loading) return null;
    let strstatus;
    if(this.state.status===0){
      strstatus="草稿"
    }else if(this.state.status===1)
    {
      strstatus="审核中"
    }else
    {
      strstatus="已审核"
    };
    return(
      <div>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
         <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="日期">
            <DatePicker
              locale={locale}
              style={{ width:  400 }}
              value={this.state.bill_date}
               onChange={this.bill_dateonchange}
              placeholder="日期"
              disabled ={this.fieldedit("bill_date")}
              autoFocus
            />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="状态">
              <Input
                value={strstatus}
                style={{ width:  400 }}
                placeholder="状态"
                disabled="disabled"
              />
						</Form.Item>
				  </Col>
        </Row>
      <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同">
              <Select style={{ width:  400 }} value={this.state.contractsid} onChange={value => this.setState({contractsid:value})}  
              disabled ={this.fieldedit("contractsid")}>
               {(this.state.contractsdata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.code +' ' + item.name}</Select.Option>
              ))}
              </Select>
            </Form.Item>
          </Col>
				  {/* <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="进度(%)">
              <Input
                value={this.state.percent}
                style={{ width:  400 }}
                onChange={this.percentChange}
                placeholder="进度(%)"
                onkeyup="this.value=this.value.replace(/\D/g,'')"
                onafterpaste="this.value=this.value.replace(/\D/g,'')"
                type="number"
                disabled ={this.fieldedit("percent")}
              />
						</Form.Item>
				  </Col> */}
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="编码">
              <Input
                value={this.state.code}
                style={{ width:  400 }}
                onChange={e => this.setState({code:e.target.value})}
                placeholder="编码"
                disabled ={this.fieldedit("code")}
                autoFocus
              />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="名称">
              <Input
                value={this.state.name}
                style={{ width:  400 }}
                onChange={e => this.setState({name:e.target.value})}
               disabled ={this.fieldedit("name")}
                placeholder="名称"
              />
						</Form.Item>
				  </Col>
        </Row>

        <Row >
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="记录事项">
              <textarea
                rows="5" cols="60"
                textAlignVertical="top"
                height="100px"
                value={this.state.message}
                onChange={e => this.setState({message:e.target.value})}
                placeholder="记录事项"
                disabled ={this.fieldedit("message")}
              />
						</Form.Item>
				  </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="附件">
              <Upload {...this.getPdfURL()} fileList={this.state.annex} 
              disabled ={this.fieldedit("annex")}>
                <Button>
                  <UploadOutlined /> 上传
                </Button>
              </Upload>
						</Form.Item>
				  </Col>
        </Row>
      </Form>
      </div>
    );
  };
}
